package cn.tom.service.impl;

import cn.tom.dao.LargeFileDao;
import cn.tom.entity.LargeFile;
import cn.tom.service.LargeFileService;
import cn.tom.tools.Base64ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service("fs")
public class LargeFileServiceImpl implements LargeFileService {
    @Resource
    private LargeFileDao largeFileDao;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void add(String id, String filename, byte[] content) {
        LargeFile lf = new LargeFile();
        lf.setId(id);
        lf.setFilename(filename);
        lf.setContent(content);
        int add = largeFileDao.add(lf);
        if(add >= 1){
            String s = Base64ImageUtils.encodeImageToBase64(content);
            lf.setContent(s);
            redisTemplate.opsForValue().set("t_file:" + lf.getId() ,
                    lf , 10 * 60 * 1000 , TimeUnit.SECONDS);

        }
    }

    @Override
    public String getString(String id) {
        return (String)largeFileDao.findOne(id).getContent();
    }

    @Override
    public LargeFile findOne(String id) {
        LargeFile lf = null;
        Object o = redisTemplate.opsForValue().get("t_file:" + id);
        lf = (LargeFile) o;
        if(lf == null){
            lf = largeFileDao.findOne(id);
            redisTemplate.opsForValue().set("t_file:" + id , lf , 10 * 60 * 1000 , TimeUnit.SECONDS);
        }
        return lf;
    }

    @Override
    public void delete(String id) {
        largeFileDao.delete(id);
        redisTemplate.delete("t_file:" + id);
    }
}
